import { useState, useEffect } from 'react';

/**
 * 管理组件进入/退出动画状态的自定义钩子
 * @param open - 控制组件可见性的布尔值
 * @param animationDuration - 动画持续时间(毫秒)
 * @returns 一个包含 shouldRender 和 animationState 的对象
 */
export const useAnimation = (open: boolean, animationDuration: number = 300) => {
  const [shouldRender, setShouldRender] = useState(false);
  const [animationState, setAnimationState] = useState<'entering' | 'entered' | 'exiting' | 'exited'>('exited');

  useEffect(() => {
    if (open) {
      setShouldRender(true);
      setAnimationState('entering');
      const enterTimer = setTimeout(() => {
        setAnimationState('entered');
      }, 10); // 短暂延迟以确保初始状态被渲染

      return () => clearTimeout(enterTimer);
    } else if (shouldRender) {
      setAnimationState('exiting');
      const exitTimer = setTimeout(() => {
        setAnimationState('exited');
        setShouldRender(false);
      }, animationDuration);

      return () => clearTimeout(exitTimer);
    }
  }, [open, shouldRender, animationDuration]);

  return { shouldRender, animationState };
};
